from django.http import Http404
from django.core.exceptions import PermissionDenied
from rest_framework.views import set_rollback
from rest_framework import exceptions
from rest_framework.views import Response


class MagBaseException(exceptions.APIException):
    # """基类定义基本的异常"""
    code = 10000  # code为0表示正常，非0都是错误
    message = '非法请求'  # 错误描述

    @classmethod
    def get_message(cls):
        return {'code': cls.code, 'message': cls.message}


class InvalidUsernameOrPassword(MagBaseException):
    code = 2
    message = '用户名或密码错误'

class InvalidToken(MagBaseException):
    code = 1
    message = "登录过期，请重新登录"


class  InvalidPassword(MagBaseException):
    code = 101
    message = '密码验证失败'


# code <100 ，前端清除token，跳转到登录页。

# 内部异常暴露细节
exc_map = {
    'AuthenticationFailed': InvalidUsernameOrPassword,
    'InvalidToken': InvalidToken
}


def global_exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    print('异常', '=' * 30)
    print(type(exc), exc.__dict__)
    print('=' * 30)

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait
        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}
        set_rollback()

        if isinstance(exc, MagBaseException):
            errmsg = exc.get_message()
        else:
            errmsg = exc_map.get(exc.__class__.__name__, MagBaseException).get_message()
        return Response(errmsg, status=200)  # 状态恒为200
        # return Response(data, status=exc.status_code, headers=headers)
    return None
